package com.kborid.musicplayer.Tools;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.util.ArrayList;

import android.text.TextUtils;
import android.util.Log;

/**
 * 默认的歌词解析器
 */
public class DefaultLrcParser {
	private static final String TAG = "DefaultLrcParser";
	private static final DefaultLrcParser istance = new DefaultLrcParser();

	public static final DefaultLrcParser getIstance() {
		return istance;
	}

	/**
	 * 获取歌词List集合
	 * 
	 * @return
	 */
	public ArrayList<LrcRowInfo> getLrcRows(File file) {
		ArrayList<LrcRowInfo> rows = null;
		BufferedReader br = null;
		try {
			FileInputStream stream = new FileInputStream(file);
			br = new BufferedReader(new InputStreamReader(stream, "GB2312"));
			String line;
			StringBuffer sb = new StringBuffer();
			while ((line = br.readLine()) != null) {
				sb.append(line + "\n");
			}
			rows = getLrcRows(sb.toString());
			br.close();
			stream.close();
		} catch (Exception e) {
			Log.i(TAG, "e = " + e.getMessage());
		}
		return rows;
	}

	/***
	 * 将歌词文件里面的字符串 解析成一个List<LrcRow>
	 */
	private ArrayList<LrcRowInfo> getLrcRows(String str) {
		ArrayList<LrcRowInfo> lrcRows = new ArrayList<LrcRowInfo>();
		if (TextUtils.isEmpty(str)) {
			return null;
		}
		BufferedReader br = new BufferedReader(new StringReader(str));
		String lrcLine;
		try {
			while ((lrcLine = br.readLine()) != null) {
				ArrayList<LrcRowInfo> rows = LrcRowInfo.createRows(lrcLine);
				if (rows != null && rows.size() > 0) {
					lrcRows.addAll(rows);
				}
			}
			for (int i = 0; i < lrcRows.size() - 1; i++) {
				lrcRows.get(i)
						.setTotalTime(
								lrcRows.get(i + 1).getTime()
										- lrcRows.get(i).getTime());
			}
			lrcRows.get(lrcRows.size() - 1).setTotalTime(5000);
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		} finally {
			if (br != null) {
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
		// 按时间排序
		for (int i = 0; i < lrcRows.size() - 1; i++) {
			for (int j = i + 1; j < lrcRows.size(); j++) {
				if (lrcRows.get(i).getTime() > lrcRows.get(j).getTime()) {
					LrcRowInfo tmp = lrcRows.get(i);
					lrcRows.set(i, lrcRows.get(j));
					lrcRows.set(j, tmp);
				}
			}
		}

		return lrcRows;
	}

}
